import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ProdCons_BlockQueueDemo {
    public static void main(String[] args) {
        MyResource resource = new MyResource(new ArrayBlockingQueue<>(10));

        new Thread(()->{
            System.out.println(Thread.currentThread().getName() + "\t开始生产");
            try {
                resource.myProd();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"Producer").start();

        new Thread(()->{
            System.out.println(Thread.currentThread().getName() + "\t开始消费");
            try {
                resource.myCons();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"Consumer").start();


        try {
            TimeUnit.SECONDS.sleep(5);
            resource.stop();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class MyResource{
    private volatile boolean FLAG = true;
    private AtomicInteger atomicInteger = new AtomicInteger();
    BlockingQueue queue = null;
    public MyResource(BlockingQueue<String> queue){
        this.queue = queue;
        System.out.println(queue.getClass().getName());
    }

    public void  myProd() throws InterruptedException {
        String data;
        boolean retValue;
        while (FLAG){
            data = atomicInteger.incrementAndGet() + "";
            retValue = queue.offer(data, 2L, TimeUnit.SECONDS);
            if (retValue)
                System.out.println(Thread.currentThread().getName() + "\t插入队列成功,插入数据为:" + data);
            else
                System.out.println(Thread.currentThread().getName() + "\t插入队列失败!插入数据为:" + data);
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(Thread.currentThread().getName() + "\t停止生产动作");
    }

    public void  myCons() throws InterruptedException {
        String data;
        while (FLAG){
            data = (String) queue.poll(2L, TimeUnit.SECONDS);
            if(null == data || data.equalsIgnoreCase("")){
                FLAG = false;
                System.out.println("超过2秒没有取到数据,退出方法");
            }
            System.out.println(Thread.currentThread().getName() + "\t获取到的数据为:" + data);
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(Thread.currentThread().getName() + "\t停止消费动作");
    }

    public void stop(){
        FLAG = false;
    }
}
